package com.wanglei.job;

import com.wanglei.domain.entity.Article;
import com.wanglei.service.ArticleService;
import com.wanglei.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 3. 定时任务每隔10分钟把Redis中的浏览量更新到数据库中
 */
@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    @Scheduled(cron = "0/20 * * * * ?")
    public void updateViewCount(){
        Map<String,Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");
        //map 转 list (先用entrySet()转set 然后set用map转list)
        List<Article> articles = viewCountMap.entrySet()
                .stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()),entry.getValue().longValue())
//                {
//                    Article article = articleService.getById(Long.valueOf(entry.getKey()));
//                    article.setViewCount(entry.getValue().longValue());
//                    return article;
//                }
                )
                .collect(Collectors.toList());
        //更新到数据库 updateBatchById 传入list<Article>可以批量修改
        articleService.updateBatchById(articles);
    }
}
